// packageA/pages/enclosureAdd/enclosureAdd.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../../utils/util');
import Base64 from '../../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:null,
    //传参来的id
    id:null,
    //是否是修改
    isEdit:false,
    //修改信息回显
    editInfo:{},
    //提交按钮禁用
    disabled:false,
    //避免表单重复提交
    code:null,
    //地区中心点-纬度
    latitude: '36.78466415549936',
    //地区中心点-经度
    longitude: '118.01429312179734',
    //标记
    markers:[],
    //圆
    circles:[],
    //半径属性
    radiusInfo:{
      color: '#FF0000DD',
      fillColor: '#7cb5ec88',
      radius: 100,
      strokeWidth: 2
    },
    minRadius: 100,
    maxRadius: 2000,
    //围栏范围取整
    radiusNum:0,
    //多边形
    polygons: [],
    //项目选择框
    showProject:false,
    //项目选择数据
    departList:[],
    //围栏类型选择框
    showType:false,
    //围栏类型选择数据
    typeList:[{
      id:1,
      text:'圆形'
    },{
      id:2,
      text:'多边形'
    }],
    //定位的地址
    address:'',
    //显示信息框
		showInfo:true,
		//选择框标题
    selectTitle:'',
    //显示选择搜索框
    showSelectSearch:false,
    //选择框搜索
    valueSearch: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.getUserProfile({
      desc: '为您提供更好的服务',
      success: (res) => {}
    })
    
    this.setData({
      code:Base64.encode(new Date() + app.globalData.userInfo.userName)
    })

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('围栏传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })

      if(paramObj.id){
        this.setData({
          id: paramObj.id,
          isEdit:true
        })
        //获取修改的数据
        this.getInfo();
      }else{
        //部门信息
        let info=app.globalData.userInfo.departObj[0];
        //定位
        this.getLocation(info);
      }
    }
  },

  //定位
  getLocation(info){  
    let province = info.area.province.name ? info.area.province.name : '暂无位置信息';
    let city = info.area.city.name ? info.area.city.name : '';
    let district = info.area.district.name ? info.area.district.name : '';
    let addressDetail = info.addressDetail ? info.addressDetail : '';

    let address=province + city + district + addressDetail;

    this.setData({
      address: address
    })
    
    let key=app.globalData.tencentKey;
    let _this=this;
    console.log('https://apis.map.qq.com/ws/geocoder/v1/?address='+address+'&key='+key);
    //地址解析
    wx.request({
		  url: 'https://apis.map.qq.com/ws/geocoder/v1/?address='+address+'&key='+key,
		  method: "GET",
		  success(res) {
        if(res.statusCode==200 && res.data){
          console.log("res");
          console.log(res);
          let info=res.data.result.location;
          
          _this.setData({
            latitude: info.lat,
            longitude: info.lng
          })

          let type=_this.data.editInfo.type;
          if(type==1){
            //圆形
            _this.showCircle();
          }else if(type==2){
            //多边形
            _this.showPolygon();
          }
        }
		  }
    })  
  },

  //显示项目选择框
  onShowProject(){
    this.setData({
			showProject: true,
      selectField: 'project',
      departList: [],
      selectTitle: '项目名称',
      showSelectSearch: true,
      valueSearch: ''
    })
    this.getProject();
  },

  //查询项目
  getProject(){
    let param = {
      isAuth: false,
      className: 'depart',
      data: {
        searchAll: true,
        selectFields: ['id','name','area','addressDetail']
      }
    }

    if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:item
          });
        });
        this.setData({
          departList: arr
        })
      }else{
        this.setData({
          departList: []
        })
      }
    }).catch((error) => {
    })  
  },

  //隐藏项目选择框
  onCloseProject(){
    this.setData({
			showProject: false
    })
  },

  //确认项目
  onConfirmProject(e){
    let departId='editInfo.departId';
    let departName='editInfo.departName';
    this.setData({
      [departId]: e.detail.value.id,
      [departName]: e.detail.value.text,
      disabled: false
    })
    
    let info=e.detail.value.obj;

    //定位到选择的项目
    this.getLocation(info);

    this.onCloseProject();
  },

  //获取输入的围栏名称
  getVal(e){
    let name='editInfo.name';
    this.setData({
			[name]: e.detail
		})
  },

  //显示围栏类型
  onShowType(){
    this.setData({
			showType: true
    })
  },  

  //隐藏围栏类型
  onCloseType(){
    this.setData({
      showType: false
    })
  },

  //确认围栏类型
  onConfirmType(e){
    let type='editInfo.type';
    let typeName='editInfo.typeName';
    let id=e.detail.value.id;
    this.setData({
      [type]:id,
      [typeName]:e.detail.value.text,
      disabled: false
    })

    if(id==1){
      //圆形
      this.showCircle();
    }else if(id==2){
      //多边形
      this.showPolygon();
    }  

    this.onCloseType();
  },

  //圆形
  showCircle(){
    //删除多边形
    this.deletePolygons();

    let td=this.data;
    let lat=td.latitude;
    let lng=td.longitude;
    let radiusInfo=td.radiusInfo;

    radiusInfo.latitude=lat;
    radiusInfo.longitude=lng;

    this.setData({    
      radiusNum:Math.round(radiusInfo.radius/100),
      circles: [radiusInfo],
      markers:[{
        latitude: Number(lat),
        longitude: Number(lng)
      }]
    })  
  },

  //滑动滑块
  onChange(event) {
    let radiusInfo=this.data.radiusInfo;
    radiusInfo.radius=event.detail;
    this.setData({
      radiusInfo:radiusInfo,
      radiusNum:Math.round(radiusInfo.radius/100),
			circles: [radiusInfo]
		})
  },

  //多边形
  showPolygon(){
    //清除圆
    this.setData({
      markers: [],
      //真机的bug，只置为空数组圆不会清除
      circles: [{
        color: '#FF0000DD',
        fillColor: '#7cb5ec88',
        radius: 1,
        strokeWidth: 2,
        latitude: null,
        longitude: null
      }]
    })
  },  

  //生成多边形
  createPolygons(){
    if(this.data.markers.length>2){
      let polygons= [];
      let obj={
        dashArray:[0, 0],
        points: this.data.markers,
        strokeWidth: 1,
        strokeColor: "#FF0000",
        fillColor: "#ff000050"
      }
      
      polygons.push(obj);
  
      this.setData({
        polygons: polygons
      })
    }else{
      Toast.fail('至少创建3个标记点');
    }
  },

  //删除多边形
  deletePolygons(){
    this.setData({
      markers: [],
      polygons: []
    })
  },

  //点击地图
  onClickMap({detail}){
    let type=this.data.editInfo.type;
    if(type==1){
      this.setData({
        latitude: detail.latitude,
        longitude: detail.longitude
      })
      //逆地址解析
      this.getAddress();

    }else if(type==2){
      //生成标记点
      let arr=[];
      let obj={
        latitude: detail.latitude,
        longitude: detail.longitude 
      }
    
      arr.push(obj);

      this.setData({
        markers: arr.concat(this.data.markers)
      })
    }  
  },

  //逆地址解析
  getAddress(){
    let _this=this;
    let location=this.data.latitude+','+this.data.longitude;
    let key=app.globalData.tencentKey;

    wx.request({
		  url: 'https://apis.map.qq.com/ws/geocoder/v1/?location='+location+'&key='+key+'&get_poi=1',
		  method: "GET",
		  success(res) {
        if(res.statusCode==200 && res.data){
          _this.setData({
            address: res.data.result.address
          })

          _this.showCircle();
        }
		  }
		})
  },

  //保存围栏
  saveEnclosure(){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })

    let td=this.data;
    let editInfo=td.editInfo;
    let departObj=app.globalData.userInfo.departObj[0];
    
    if(!editInfo.departId){
      Toast.fail('请选择项目');
      return;
    }
    
    if(editInfo.name==null || !editInfo.name.trim()){
      Toast.fail('请输入围栏名称');
      return;
    }

    if(!editInfo.type){
      Toast.fail('请选择围栏类型');
      return;
    }

    //半径和定位点
    let radius=0;

    if(editInfo.type==1){
      radius=td.circles[0].radius;
    }else if(editInfo.type==2){
      if(!td.polygons.length){
        Toast.fail('没有画多边形');
        return;
      }
      radius=0;
    } 
    
    //权限
    let authArr=[departObj.id, departObj.companyId, editInfo.departId];
    let authSet=new Set(authArr);
    authArr=Array.from(authSet);

    let param={
      className:'personnelFence',
      data:{
        requestToken: td.code,
        id: td.id,
        name: editInfo.name.trim(),
        radius: radius,
        departId: editInfo.departId,
        departName: editInfo.departName,
        dataAuthority: {
          depart: authArr
        },
        type: editInfo.type,
        points: td.markers,
        lat: td.markers[0].latitude+'',
        lng: td.markers[0].longitude+'',
        address: td.address
      }
    }

    if(!td.isEdit){
      param.data.createUser=app.globalData.userInfo.id;
    }

    //console.log(param);

    //避免表单重复提交
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '数据提交中...'
    });
    
    CommonService.goSave(param).then(res=>{
      this.setData({
        disabled:false
      })
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('成功');

        //同步es数据
        if(td.isEdit){
          this.synchronFence(param.data);
        }

        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);

      }else if(res.statusCode==202){
        Toast.fail('您操作太快了,请勿重复提交');
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
  },

  //获取修改的数据
  getInfo(){
    let param = {
      isAuth: false,
      className: 'personnelFence',
      data: {
        id: this.data.id,
        selectFields: ['id','name','radius','departId','departName','type','points','lat','lng','address']
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result[0];
        console.log('围栏信息回显');
        console.log(result);

        this.setData({
          longitude: result.lng,
          latitude: result.lat,
          address: result.address
        })
        
        //字符串转化为数值类型（有些数据存的是字符串）
        result.points.forEach(item => {
          item.latitude=Number(item.latitude);
          item.longitude=Number(item.longitude);
        });

        //按类型显示不同的围栏
        if(result.type==1){
          result.typeName='圆形';
          let radiusInfo=this.data.radiusInfo;
          radiusInfo.radius=result.radius;
          this.setData({
            radiusInfo: radiusInfo
          })
          this.showCircle();
        }else if(result.type==2){
          this.setData({
            markers: result.points
          })
          result.typeName='多边形';
          this.createPolygons();
        }

        this.setData({
          editInfo: result
        })
      }
    }).catch((error) => {
    })
  },

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.refreshListAndPage();
    wx.navigateBack();
  },

  //切换信息框
  onSwitchInfo(){
    this.setData({
      showInfo: !this.data.showInfo
    })
  },

  //同步es数据
  synchronFence(obj){
    let param={
      name: obj.name,
      departId: obj.departId,
      id: obj.id,
      radius: obj.radius,
      type: obj.type,
      points: obj.points
    }
    CommonService.synchronFence(param).then(res=>{
    }).catch((error) => {
    })
	},
	
	//选择框搜索
  onChangeSelectVal(e){
    let selectField=this.data.selectField;

    this.setData({
      valueSearch: e.detail
    })

    //项目
    if(selectField=='project'){
      this.getProject();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})